#include "./door.h"
#include "../rtx/rtx_os.h"
#include "../xlib/gpio.h"


namespace driver {

Door door;

using namespace stm32f1;

namespace door_impl {

using namespace gpio;

using ELOCK = Cfg<PC<15>, Mode::OUT_50MHz_PP>;
using STATUS = Cfg<PB<0>, Mode::INPUT_FLOAT>;
using SENSOR = Cfg<PB<1>, Mode::INPUT_FLOAT>;

} // namespace door_impl

using namespace door_impl;
using namespace utils;

void Door::init() {
    rcc::enable<ELOCK, STATUS, SENSOR>();
    gpio::config<ELOCK, STATUS, SENSOR>();
    ELOCK::clr();
}

bool Door::is_close() const { return !SENSOR::read(); }

bool Door::is_lock() const { return !STATUS::read(); }

Error Door::open() {
    ELOCK::clr();
    osDelay(500);
    if (is_lock() || is_close()) {
        return ec::DOOR_OPEN_FAIL;
    }
    return ec::OK;
}

Error Door::close() {
    ELOCK::set();
    osDelay(500);
    if ((!is_lock()) || (!is_close())) {
        return ec::DOOR_OPEN_FAIL;
    }
    return ec::OK;
}

} // namespace driver
